package com.gdou.teaching.service.impl;

import com.gdou.teaching.Enum.ResultEnum;
import com.gdou.teaching.dataobject.File;
import com.gdou.teaching.dto.FileDTO;
import com.gdou.teaching.exception.TeachingException;
import com.gdou.teaching.mapper.FileMapper;
import com.gdou.teaching.service.FileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: teaching
 * @Package: com.gdou.teaching.service.impl
 * @ClassName: FileServiceImpl
 * @Author: carrymaniac
 * @Description:
 * @Date: 2019/11/8 2:57 下午
 * @Version:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    FileMapper fileMapper;

    @Override
    public FileDTO selectFileById(Integer fileId) {
        File file = fileMapper.selectFileByFileId(fileId);
        FileDTO fileDTO = new FileDTO();
        BeanUtils.copyProperties(file,fileDTO);
        return fileDTO;
    }

    @Override
    public List<FileDTO> selectFileByCategoryAndFileCategoryId(Integer fileCategory, Integer fileCategoryId) {
        List<File> files = fileMapper.selectFileByFileCategoryAndFileCategoryIdOrderByCreateTime(fileCategory, fileCategoryId);
        List<FileDTO> FileDTOs = files.stream().map(file -> {
            FileDTO fileDTO = new FileDTO();
            BeanUtils.copyProperties(file, fileDTO);
            return fileDTO;
        }).collect(Collectors.toList());
        return FileDTOs;
    }

    @Override
    public List<FileDTO> selectFileByCategoryAndFileCategoryIdAndKeyword(Integer fileCategory, Integer fileCategoryId, String keyword) {
        List<File> files = fileMapper.selectFileByFileCategoryAndFileCategoryIdOrderAndKeywordByCreateTime(fileCategory, fileCategoryId,keyword);
        List<FileDTO> FileDTOs = files.stream().map(file -> {
            FileDTO fileDTO = new FileDTO();
            BeanUtils.copyProperties(file, fileDTO);
            return fileDTO;
        }).collect(Collectors.toList());
        return FileDTOs;
    }

    @Override
    public int saveFile(Integer fileCategory, Integer fileCategoryId, List<FileDTO> FileDTOs) {
        List<File> files = FileDTOs.stream().map(fileDTO -> {
            File file = new File();
            BeanUtils.copyProperties(fileDTO, file);
            file.setFileCategory(fileCategory);
            file.setFileCategoryId(fileCategoryId);
            file.setFileStatus(0);
            return file;
        }).collect(Collectors.toList());
        files.stream().forEach(file -> {
            try{
                fileMapper.addFile(file);
            }catch (Exception e) {
                throw new TeachingException(ResultEnum.FILE_ERROR);
            }
        });
        return 1;
    }
}
